package Web;

import Words.Mapper.WordMapper;
import Words.Pojo.Word;
import Words.Test.Tests;
import Words.Utils.MybatisUtils;
import com.alibaba.fastjson.JSON;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;


@WebServlet("/Index")
public class Index  extends HttpServlet {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    WordMapper wordMapper = sqlSession.getMapper(WordMapper.class);
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String key = req.getParameter("key");
//        System.out.println(key);
        key= key.replaceAll(" ", "").toLowerCase();
        Tests tests=new Tests();
        Random random=new Random();
        int randomInt = random.nextInt(14117);
        List<Word> searchresoult = wordMapper.GetWordBiganOfKey(key,randomInt);
        Map<String ,Object> map=new HashMap<>();
        resp.setHeader("Access-Control-Allow-Origin", "*");
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter pw = resp.getWriter();
//        for (Word word:searchresoult){
//            System.out.println(Arrays.toString(word.getInformation()));
//        }
        map.put("word",searchresoult);
        String json = JSON.toJSONString(map);
        pw.print(json);
    }
}
